package com.itchu.system.service.impl;

import com.itchu.common.exption.ExceptionEnum;
import com.itchu.common.exption.MusicException;
import com.itchu.system.domain.Score;
import com.itchu.system.mapper.ScoreMapper;
import com.itchu.system.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Transactional
public class ScoreServiceImpl implements ScoreService {

    @Autowired
    private ScoreMapper scoreMapper;

    @Override
    public void addScore(Score score) {

        Score recore = new Score();
        recore.setSonglistId(score.getSonglistId());
        recore.setUserId(score.getUserId());

        List<Score> list = scoreMapper.select(recore);
        if (!CollectionUtils.isEmpty(list)) {
            throw new MusicException(ExceptionEnum.MUSIC_ALREDY_SCORE);
        }
        scoreMapper.insert(score);
    }

    @Override
    public Double getAvgScore(Long songlistId) {
        Score recore = new Score();
        recore.setSonglistId(songlistId);
        List<Score> list = scoreMapper.select(recore);

        if (CollectionUtils.isEmpty(list)) {
            return 0.0;
        }

        Double avgScore = 0.0;

        Long totalScore = list.stream().map(Score::getScore).reduce(Long::sum).get();

        avgScore = Double.valueOf(totalScore / list.size());


        return avgScore;
    }
}
